<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>python文件操作 | Cucy的博客</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="python">
    <meta name="description" content="文件操作">
<meta property="og:type" content="article">
<meta property="og:title" content="python文件操作">
<meta property="og:url" content="http://zhourudong.cn/2017/02/18/26-python文件操作/index.html">
<meta property="og:site_name" content="Cucy的博客">
<meta property="og:description" content="文件操作">
<meta property="og:image" content="https://raw.githubusercontent.com/cucyzrd/file/master/python/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C.png">
<meta property="og:updated_time" content="2019-02-22T05:28:07.813Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python文件操作">
<meta name="twitter:description" content="文件操作">
<meta name="twitter:image" content="https://raw.githubusercontent.com/cucyzrd/file/master/python/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C.png">
    
        <link rel="alternate" type="application/atom+xml" title="Cucy的博客" href="/atom.xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.6.13">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.png">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">cucy</h5>
          <a href="mailto:292016176@qq.com" title="292016176@qq.com" class="mail">292016176@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/cucy" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">python文件操作</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">python文件操作</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-02-18T04:25:16.000Z" itemprop="datePublished" class="page-time">
  2017-02-18
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#文件操作"><span class="post-toc-number">1.</span> <span class="post-toc-text">文件操作</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#目录操作"><span class="post-toc-number">2.</span> <span class="post-toc-text">目录操作</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#创建目录"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">创建目录</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#遍历目录"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">遍历目录</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#路径相关的操作"><span class="post-toc-number">3.</span> <span class="post-toc-text">路径相关的操作</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#序列化、反序列化"><span class="post-toc-number"></span> <span class="post-toc-text">序列化、反序列化</span></a>
        </nav>
    </aside>
    
<article id="post-26-python文件操作"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">python文件操作</h1>
        <div class="post-meta">
            <time class="post-time" title="2017-02-18 12:25:16" datetime="2017-02-18T04:25:16.000Z"  itemprop="datePublished">2017-02-18</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h2 id="文件操作"><a href="#文件操作" class="headerlink" title="文件操作"></a>文件操作</h2><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://raw.githubusercontent.com/cucyzrd/file/master/python/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C.png" alt title>
                </div>
                <div class="image-caption"></div>
            </figure>
<a id="more"></a>
<h2 id="目录操作"><a href="#目录操作" class="headerlink" title="目录操作"></a>目录操作</h2><h3 id="创建目录"><a href="#创建目录" class="headerlink" title="创建目录"></a>创建目录</h3><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line">mkdir(path, mode=<span class="number">511</span>, *, dir_fd=<span class="keyword">None</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># os.mkdir 不能递归的创建目录</span></span><br><span class="line">os.mkdir(<span class="string">'/tmp/test2/test3'</span>) </span><br><span class="line"></span><br><span class="line"><span class="comment"># os.makedirs 可以递归的创建目录 (类似linux mkdir -p)</span></span><br><span class="line">os.makedirs(<span class="string">'/tmp/test2/test3'</span>) <span class="comment"># mkdir -p /tmp/test2/test3</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 当目录已经存在时， mkdir 和makedirs都会抛出异常</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 只能删除空目录，不能删除非空目录</span></span><br><span class="line">os.rmdir(<span class="string">'/tmp/test'</span>) <span class="comment"># rmdir /tmp/test</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 递归的删除空目录</span></span><br><span class="line">os.removedirs(<span class="string">'/tmp/test2/test3/'</span>) </span><br><span class="line"></span><br><span class="line"><span class="comment"># rm -rf /tmp/test  递归删除目录</span></span><br><span class="line"><span class="keyword">import</span> shutil</span><br><span class="line">shutil.rmtree(<span class="string">'/tmp/test'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 移动</span></span><br><span class="line">shutil.move(<span class="string">'/tmp/test2'</span>, <span class="string">'/tmp/test'</span>) <span class="comment"># 和mv命令的表现完全一致</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 复制</span></span><br><span class="line">shutil.copytree(<span class="string">'/tmp/a'</span>, <span class="string">'/tmp/d'</span>, symlinks=<span class="keyword">True</span>) <span class="comment"># cp -rpP</span></span><br></pre></td></tr></table></figure>
<h3 id="遍历目录"><a href="#遍历目录" class="headerlink" title="遍历目录"></a>遍历目录</h3><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line"><span class="comment"># 目录列表</span></span><br><span class="line">os.listdir()  <span class="comment">#  ls -a</span></span><br></pre></td></tr></table></figure>
<h2 id="路径相关的操作"><a href="#路径相关的操作" class="headerlink" title="路径相关的操作"></a>路径相关的操作</h2><figure class="highlight python"><table><tr><td class="code"><pre><span class="line">basename</span><br><span class="line">dirname</span><br><span class="line">join</span><br><span class="line">split</span><br><span class="line">abspath</span><br><span class="line">getcwd</span><br><span class="line"></span><br><span class="line">os.path.join(<span class="string">'/'</span>, <span class="string">'tmp'</span>, <span class="string">'d'</span>, <span class="string">'a'</span>)</span><br><span class="line"><span class="string">'/tmp/d/a'</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># -&gt; (dirname, basename)</span></span><br><span class="line">os.path.split(<span class="string">'/tmp/d/a/file'</span>)</span><br></pre></td></tr></table></figure>
<h1 id="序列化、反序列化"><a href="#序列化、反序列化" class="headerlink" title="序列化、反序列化"></a>序列化、反序列化</h1><ul>
<li>序列化 对象 -&gt; str/bytes</li>
<li>反序列化 str/bytes -&gt; 对象</li>
</ul>
<figure class="highlight"><table><tr><td class="code"><pre><span class="line">import pickle</span><br><span class="line"># 序列化</span><br><span class="line">pickle.dumps(1) </span><br><span class="line"></span><br><span class="line">pickle.dumps(&#123;'a': 1&#125;)</span><br><span class="line">b'\x80\x03&#125;q\x00X\x01\x00\x00\x00aq\x01K\x01s.'</span><br><span class="line"></span><br><span class="line"># </span><br><span class="line">pickle.dump -&gt; fileobjec</span><br><span class="line">pickle.dumps -&gt; bytes</span><br><span class="line"></span><br><span class="line">pickle 的序列化与反序列化，能针对大多数的Python对象包括方法</span><br><span class="line">pickle是Python特有的， 只能在Python之间传递数据使用</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">import json</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># json 仅仅可以序列化 int float, bool, None, str, list dict</span><br></pre></td></tr></table></figure>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2019-02-22T05:28:07.813Z" itemprop="dateUpdated">2019-02-22 13:28:07</time>
</span><br>


        
        <a href="/2017/02/18/26-python文件操作/" target="_blank" rel="external">http://zhourudong.cn/2017/02/18/26-python文件操作/</a>
        
    </div>
    <footer>
        <a href="http://zhourudong.cn">
            <img src="/img/avatar.png" alt="cucy">
            cucy
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/python/">python</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://zhourudong.cn/2017/02/18/26-python文件操作/&title=《python文件操作》 — Cucy的博客&pic=http://zhourudong.cn/img/avatar.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://zhourudong.cn/2017/02/18/26-python文件操作/&title=《python文件操作》 — Cucy的博客&source=文件操作
                
                    
                    
             ..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://zhourudong.cn/2017/02/18/26-python文件操作/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《python文件操作》 — Cucy的博客&url=http://zhourudong.cn/2017/02/18/26-python文件操作/&via=http://zhourudong.cn" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://zhourudong.cn/2017/02/18/26-python文件操作/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/02/20/27-python面向对象/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">python面向对象</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/02/17/25-python-奇淫巧技/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">python 奇淫巧技</h4>
      </a>
    </div>
  
</nav>



    














</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢大爷~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/img/wechat.jpg" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="/img/wechat.jpg" data-alipay="/img/alipay.jpg">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>cucy &copy; 2016 - 2021</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://zhourudong.cn/2017/02/18/26-python文件操作/&title=《python文件操作》 — Cucy的博客&pic=http://zhourudong.cn/img/avatar.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://zhourudong.cn/2017/02/18/26-python文件操作/&title=《python文件操作》 — Cucy的博客&source=文件操作
                
                    
                    
             ..." data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://zhourudong.cn/2017/02/18/26-python文件操作/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《python文件操作》 — Cucy的博客&url=http://zhourudong.cn/2017/02/18/26-python文件操作/&via=http://zhourudong.cn" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://zhourudong.cn/2017/02/18/26-python文件操作/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://zhourudong.cn/2017/02/18/26-python文件操作/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };


</script>

<script src="/js/main.min.js?v=1.6.13"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.6.13" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '死鬼去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
